package com.ruoyi.jihuo.service.handler;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.jihuo.config.FieldDisposeConfig;
import com.ruoyi.jihuo.domain.JhTmAccount;
import com.ruoyi.jihuo.domain.JhTmGoods;
import com.ruoyi.jihuo.domain.JhTmTemplate;
import com.ruoyi.jihuo.domain.Sku;
import com.ruoyi.jihuo.quzrtz.SubmitItem;
import com.taobao.top.schema.enums.FieldTypeEnum;
import com.taobao.top.schema.exception.TopSchemaException;
import com.taobao.top.schema.factory.SchemaReader;
import com.taobao.top.schema.factory.SchemaWriter;
import com.taobao.top.schema.field.*;
import com.taobao.top.schema.option.Option;
import com.taobao.top.schema.value.ComplexValue;
import com.taobao.top.schema.value.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author：LXY
 * @DATE：2025-09-15 09:12
 * @Description：
 */
@Slf4j
@Component
public class Jh80SubmitItemHandler implements PriorityHandler{
    @Autowired
    private SubmitItem submitItem;
    @Override
    public int getPriority() {
        return 80;
    }

    @Override
    public boolean handle(ProcessContext<JSONObject> request) throws IOException {
        JSONObject data = request.getData();
        JhTmGoods item = data.getObject("item", JhTmGoods.class);
        JhTmAccount jhTmAccount = data.getObject("tmAccount", JhTmAccount.class);
        Map<String, String> categoryData = item.getJhCatProp();
        String jhDesc = item.getJhDesc();
        Map<String, String> colorUrlMap = data.getObject("colorUrlMap", HashMap.class);
        Map<String, String> descUrlMap = data.getObject("descUrlMap", HashMap.class);
        List<String> mainPic = data.getList("uploadMainPic", String.class);
        String submitItemSchema = data.getString("submitItemSchema");
        BigDecimal templatePrice = data.getObject("template", JhTmTemplate.class).getJhPrice();
        // 不需要处理的key
        List<String> ignoreKeys = new ArrayList<>();
        ignoreKeys.add("wireless_desc");
        double priceRatio;
        if (templatePrice != null) {
            priceRatio = templatePrice.doubleValue(); // 直接使用BigDecimal的doubleValue方法转换为double
        } else {
            priceRatio = 1.0; // 如果price为null，则设置为1.0
        }
        AtomicReference<Double> lowPrice = new AtomicReference<>(999999.0);
        JSONArray skuJsonArray = data.getJSONArray("skuList");
        List<Sku> skuList = skuJsonArray.toJavaList(Sku.class);
        Map<String, Field> stringFieldMap = null;
        try {
            if (submitItemSchema == null) {
                request.setErrorInfo("提交商品schema为空");
                throw new RuntimeException("提交商品schema为空");
            }
            stringFieldMap = SchemaReader.readXmlForMap(submitItemSchema);
        } catch (TopSchemaException e) {
            request.setErrorInfo("读取提交商品的schema异常:" + e.getMessage());
            throw new RuntimeException("读取提交商品的schema异常:" + e.getMessage());
        }
        for (Map.Entry<String, Field> entry : stringFieldMap.entrySet()) {
            String k = entry.getKey();
            if (ignoreKeys.contains(k)){
                continue;
            }
            Field v = entry.getValue();
            String name = v.getName();
            if ("prop_20000".equals(k)) {
                // todo 暂时没看到过一个店铺多个品牌场景，如果有后面再改
                ((SingleCheckField) v).getOptions().forEach(o -> {
                    // 应该是店铺默认品牌
                    if (o.getDisplayName().equals(jhTmAccount.getJhName())) {
                        ((SingleCheckField) v).setValue(o.getValue());
                    }
                });
                continue;
            }
            // todo 主图？ 最新规则里好像没有
            if ("产品图片".equals(name)) {
                ((ComplexField) v).getFieldList().forEach(f -> {
                });
            }
            // 默认中文
            if ("lang".equals(k)) {
                ((SingleCheckField) v).setValue("zh_CN");
                continue;
            }
            // 商品数量，应该从 数据源 与 模板同时确定
            if ("quantity".equals(k)) {
                ((InputField) v).setValue(item.getJhQuantity().toString());
                continue;
            }

            if ("main_video".equals(k)) {
                ComplexValue complexValue = ((ComplexField) v).getComplexValue();
                complexValue.setInputFieldValue("main_video_id", item.getJhVideo());
                continue;
            }
            // 运费信息 ? todo 运费模板获取
            // freight_payer freight_by_buyer freight postage_id
            if ("freight_payer".equals(k)) {
                ((SingleCheckField) v).setValue("2");
                continue;
            }
            if ("freight_by_buyer".equals(k)) {
                Value vvv = new Value();
                ((SingleCheckField) v).setValue(vvv);
                continue;
            }
            if ("freight".equals(k)) {
                ((ComplexField) v).setComplexValue(null);
                continue;
            }
            if ("item_images".equals(k)) {
                ComplexValue complexValue = new ComplexValue();
                complexValue.setInputFieldValue("item_image_0", mainPic.get(0));
                complexValue.setInputFieldValue("item_image_1", mainPic.get(1));
                complexValue.setInputFieldValue("item_image_2", mainPic.get(2));
                complexValue.setInputFieldValue("item_image_3", mainPic.get(3));
                complexValue.setInputFieldValue("item_image_4", mainPic.get(4));
                ((ComplexField) v).setComplexValue(complexValue);
                continue;
            }
            // 透明图 , 选择用主图第一张
            // 图片像素必须是800*800
            if ("white_bg_image".equals(k)) {
                ((InputField) v).setValue(mainPic.get(0));
                continue;
            }
            // value =0 代表上架到橱窗 2代表到仓库
            if ("item_status".equals(k)) {
                String jhListingSet = jhTmAccount.getJhListingSet(); //0上架到仓库   1上架到橱窗
                String value = "2";
                if ("1".equals(jhListingSet)) {
                    value = "0";
                }
                ((SingleCheckField) v).setValue(value);
                continue;
            }
            if ("title".equals(k)) {
                ((InputField) v).setValue(item.getJhTitle());
                continue;
            }

            if ("description".equals(k)) {
                if (v instanceof InputField) {
                    ((InputField) v).setValue(descChange(jhDesc, descUrlMap));
                    continue;
                }
                if (v instanceof ComplexField) {
                    //每个商品描述 的fields中的第一个元素 应该都是一样的，直接就给第一个元素中的fields中的第一个元素赋值 v.fields[0].fields[0]
                    ComplexValue firstComplexValue = new ComplexValue();
                    ComplexValue secondComplexValue = new ComplexValue();
                    // todo 需要测一下放到这里好不好使
                    secondComplexValue.setInputFieldValue(((ComplexField)((ComplexField) v).getFieldList().get(0)).getFieldList().get(0).getId(),descChange(jhDesc, descUrlMap));
                    firstComplexValue.setComplexFieldValue(((ComplexField) v).getFieldList().get(0).getId(),secondComplexValue);
                    ((ComplexField) v).setComplexValue(firstComplexValue);
                }
            }
            // 是否支持会员折扣
            if ("auction_point".equals(k)) {
                // 输入模板值
                continue;
            }

            // 颜色分类扩展
            if ("prop_extend_1627207".equals(k)) {
                HashMap<String, Option> imageOptionMap = new HashMap<>();
                Map<String, Field> fieldMap = ((MultiComplexField) v).getFieldMap();
                SingleCheckField prop_1627207 = (SingleCheckField) fieldMap.get("prop_1627207");
                prop_1627207.getOptions().forEach(o -> {
                    imageOptionMap.put(o.getDisplayName(), o);
                });

                colorUrlMap.forEach((imageName, imageUrl) -> {
                    ComplexValue complexValue = new ComplexValue();
                    complexValue.setInputFieldValue("in_prop_1627207", new Value(imageName));
                    complexValue.setInputFieldValue("prop_image", new Value(imageUrl));
                    complexValue.setSingleCheckFieldValue("prop_1627207", new Value(imageOptionMap.getOrDefault(imageName, imageOptionMap.get("其它")).getValue()));
                    ((MultiComplexField) v).addComplexValue(complexValue);
                });
                continue;
            }


            if ("sku".equals(k)) {
                buildSku((MultiComplexField) v, skuList, priceRatio, lowPrice);
                continue;
            }

            if (categoryData.containsKey(name) || FieldDisposeConfig.isRequiredFields(v)) {
                switch (v.getType()) {
                    case SINGLECHECK://单选类型
                        FieldDisposeConfig.disposeSingleCheck((SingleCheckField) v, categoryData.get(name));
                        if ("-1".equals(((SingleCheckField) v).getValue().getValue())) {
                            Field targetField = stringFieldMap.get("in_" + k);
                            if (targetField instanceof InputField) {
                                ((InputField) targetField).setValue(categoryData.get(name));
                            }
                        }
                        break;
                    case INPUT://文本输入类型
                        // 特殊处理带in 的，原key一般都是 single_check
                        if (k.startsWith("in_") && stringFieldMap.containsKey(k.substring(3))) {
                            break;
                        }
                        FieldDisposeConfig.disposeInput((InputField) v, categoryData.get(name));
                        break;
                    case MULTICHECK://多选类型
                        FieldDisposeConfig.disposeMultiCheck((MultiCheckField) v, categoryData.get(name));
                        break;
                    case MULTICOMPLEX://多复合类型
                        FieldDisposeConfig.disposeMultiComplex(v, categoryData);
                }
            }
        }
        if (lowPrice.get() >= 999999) {
            throw new RuntimeException("价格异常");
        }
        InputField price = (InputField) stringFieldMap.get("price");
        // 测试用的，价格调高，不让卖出去
        price.setValue(String.valueOf(lowPrice.get()));
        String schema = null;
        try {
            schema = SchemaWriter.writeParamXmlString(new ArrayList<>(stringFieldMap.values()));
        } catch (TopSchemaException e) {
            request.setErrorInfo("构造提交商品参数失败:"+ e.getMessage());
            throw new RuntimeException("构造提交商品参数失败:"+ e.getMessage());
        }
        data.put("schema", schema);
        submitItem.getQueue().add(data);
        // todo 这个本来是定时任务完成的，但在测试类里面不知道咋自动调用，于是就手动了
        submitItem.submit();
        return true;
    }
    private static void buildSku(MultiComplexField v, List<Sku> skuList, double priceRatio, AtomicReference<Double> lowPrice) {
        Map<String,List<Option>> fieldIdMap = new HashMap();
        v.getFieldList().forEach(field -> {
            //保存所有的fieldId
            String id = field.getId();
            //如果该字段是有选项时  保存其选项
            if (FieldTypeEnum.SINGLECHECK.equals(field.getType())) {
                fieldIdMap.put(id,((SingleCheckField) field).getOptions());
            }else {
                fieldIdMap.put(id,null);

            }
        });
        skuList.forEach(sku -> {
            ComplexValue complexValue = new ComplexValue();
            sku.getProps().forEach(prop -> {
                //判断pid在商品发布发布规则中是否存在 获取其下拉选项赋值
                if (fieldIdMap.containsKey("prop_"+prop.getPId())){
                    List<Option> options = fieldIdMap.get("prop_" + prop.getPId());
                    String optionValue = findOptionValue(options, prop);
                    complexValue.setSingleCheckFieldValue("prop_"+prop.getPId(), new Value(optionValue));
                    //为其他选项时 需要赋值in_prop_xxx字段
                    if ("-1".equals(optionValue)){
                        complexValue.setInputFieldValue("in_prop_"+prop.getPId(), prop.getVName());
                    }

                }
            });
            complexValue.setInputFieldValue("sku_price", Double.parseDouble(sku.getSkuPromoPrice()) * priceRatio + "");
            // todo 注意库存是不是也需要用模板处理
            complexValue.setInputFieldValue("sku_quantity", sku.getSkuQuantity());
            v.addComplexValue(complexValue);
            lowPrice.set(Math.min(lowPrice.get(), Double.parseDouble(sku.getSkuPromoPrice()) * priceRatio));
        });
    }
    public static String findOptionValue(List<Option> options, Sku.prop prop) {
        return options.stream()
                .filter(option -> option.getDisplayName().contains(prop.getVName()))
                .findFirst()
                .map(Option::getValue)
                .orElse("-1");
    }

    private String descChange(String desc, Map<String, String> descUrlMap) {
        String result = desc;
        for (Map.Entry<String, String> entry : descUrlMap.entrySet()) {
            // 将描述中所有匹配的key替换为对应的value
            result = result.replace(entry.getKey(), entry.getValue());
        }
        return result;
    }
}
